package com.shenyue.nbtownlet.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.support.v7.app.AlertDialog;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.chanven.lib.cptr.PtrDefaultHandler;
import com.chanven.lib.cptr.PtrFrameLayout;
import com.chanven.lib.cptr.loadmore.OnLoadMoreListener;
import com.shenyue.nbtownlet.R;
import com.shenyue.nbtownlet.adapter.HoldListViewAdapter;
import com.shenyue.nbtownlet.base.BaseActivity;
import com.shenyue.nbtownlet.databinding.ActivityHoldListQBinding;
import com.shenyue.nbtownlet.event.BaseListener;
import com.shenyue.nbtownlet.location.BDLocationManager;
import com.shenyue.nbtownlet.model.AppInsertTaskModel;
import com.shenyue.nbtownlet.model.AppLoginModel;
import com.shenyue.nbtownlet.model.DefaultModel;
import com.shenyue.nbtownlet.util.GpsUtil;
import com.shenyue.nbtownlet.util.NetWorkUtils;
import com.shenyue.nbtownlet.util.StringUtil;

/**
 * 暂存列表（随手拍和现场检查）
 */
public class HoldListQActivity extends BaseActivity implements HoldListViewAdapter.HoldListItemClickListener {
    private ActivityHoldListQBinding binding;
    private Context mContext;
    private HoldListViewAdapter listViewAdapter;
    private int pageNo = 1, pageSize = 10;
    private Handler mHandler = new Handler();
    private String islive = "-1";//0:现场检查  1:随手拍 -1全部
    private String workflowstatus = "-1";
    private String iscontainall = "-1";
    private BDLocationManager bdLocationManager = new BDLocationManager();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = DataBindingUtil.setContentView(this, R.layout.activity_hold_list_q);
        setActionBar(true, "问题单列表");
        mContext = this;
        listViewAdapter = new HoldListViewAdapter(mContext);
        binding.listView.setAdapter(listViewAdapter);
        listViewAdapter.setOnItemClickListener(this);

        binding.ptrClassicFrameLayout.setPtrHandler(new PtrDefaultHandler() {
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                if (!NetWorkUtils.isNetworkConnected(mContext)) {
                    binding.ptrClassicFrameLayout.refreshComplete();
                    showMsg(getString(R.string.no_network));
                    return;
                }
                query();
            }
        });

        binding.ptrClassicFrameLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void loadMore() {
                if (!NetWorkUtils.isNetworkConnected(mContext)) {
                    binding.ptrClassicFrameLayout.loadMoreComplete(false);
                    showMsg(getString(R.string.no_network));
                    return;
                }
                queryMore();
            }
        });
        binding.ptrClassicFrameLayout.disableWhenHorizontalMove(true);

        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                binding.ptrClassicFrameLayout.autoRefresh();
            }
        }, 32);

        updateLocation();
    }

    private void query() {
        listViewAdapter.clear();
        pageNo = 1;
        JSONObject param = new JSONObject();
        param.put("islive", islive);
        param.put("idenid", AppLoginModel.getIdentityId(mContext));
        param.put("workflowstatus", workflowstatus);
        param.put("iscontainall", iscontainall);
        param.put("pageIndex", pageNo);
        param.put("pageSize", pageSize);
        param.put("areaid", AppLoginModel.getAreaId(mContext));
        AppInsertTaskModel.GetAssessMentWorks(mContext, param, new BaseListener() {
            @Override
            public void success(String val, String action) {
                binding.ptrClassicFrameLayout.refreshComplete();
                JSONObject data = JSON.parseObject(val);
                long count = data.getLong("Count");
                JSONArray array = data.getJSONArray("LW");
                binding.ptrClassicFrameLayout.setLoadMoreEnable(!(count < pageSize));
                listViewAdapter.addItems(array);
            }

            @Override
            public void error(String error, String action) {
                binding.ptrClassicFrameLayout.refreshComplete();
                showMsg(error);
            }
        });
    }

    private void queryMore() {
        pageNo += 1;
        JSONObject param = new JSONObject();
        param.put("islive", islive);
        param.put("idenid", AppLoginModel.getIdentityId(mContext));
        param.put("workflowstatus", workflowstatus);
        param.put("iscontainall", iscontainall);
        param.put("pageIndex", pageNo);
        param.put("pageSize", pageSize);
        param.put("areaid", AppLoginModel.getAreaId(mContext));
        AppInsertTaskModel.GetAssessMentWorks(mContext, param, new BaseListener() {
            @Override
            public void success(String val, String action) {
                JSONObject data = JSON.parseObject(val);
                long count = data.getLong("Count");
                JSONArray array = data.getJSONArray("LW");
                binding.ptrClassicFrameLayout.loadMoreComplete(!(count < (pageNo * pageSize)));
                listViewAdapter.addItems(array);
            }

            @Override
            public void error(String error, String action) {
                binding.ptrClassicFrameLayout.loadMoreComplete(false);
                showMsg(error);
            }
        });
    }

    @Override
    public void onItemClick(int position) {
        if (!NetWorkUtils.isNetworkConnected(mContext)) {
            showMsg(getString(R.string.no_network));
            return;
        }
        JSONObject item = (JSONObject) listViewAdapter.getItem(position);
        Bundle bundle = new Bundle();
        String type = StringUtil.dTs(StringUtil.getValue(item.getString("MENTTYPE")));
        if (StringUtil.isNull(type))
            type = StringUtil.dTs(StringUtil.getValue(item.getString("WORKTYPE")));
        bundle.putString(DefaultModel.PAGE_DATA_ID, type);
        bundle.putString(DefaultModel.PAGE_DATA, item.toString());
        toActivity(DoTaskDetailActivity.class, bundle);
    }

    @Override
    protected void onResume() {
        super.onResume();

        if (!GpsUtil.isOPen(mContext)) {
            AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
            builder.setTitle("定位服务")
                    .setMessage("定位服务尚未打开，位置获取精度差，是否开启定位服务？")
                    .setPositiveButton("去开启", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            //跳转到设置页面让用户自己手动开启
                            Intent locationIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                            startActivity(locationIntent);
                        }
                    }).setNegativeButton("稍候再说", null);
            builder.create().show();
        } else {
            bdLocationManager.start(mContext);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        bdLocationManager.stop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        bdLocationManager.stop();
    }

    private void updateLocation() {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                Location location = bdLocationManager.getLocation();
                if (location != null) {
                    updateListUI(location);
                }
                updateLocation();
            }
        }, 2000);
    }

    private void updateListUI(Location location) {
        try {
            double longitude = Double.valueOf(StringUtil.getDoubleScale(location.getLongitude(), 8));
            double latitude = Double.valueOf(StringUtil.getDoubleScale(location.getLatitude(), 8));
            for (int i = 0, j = listViewAdapter.getCount(); i < j; i++) {
                JSONObject item = (JSONObject) listViewAdapter.getItem(i);
                if(StringUtil.isNull(item.getString("MAPY")) || StringUtil.isNull(item.getString("MAPX")))
                    continue;
                double mapy = item.getDoubleValue("MAPY");
                double mapx = item.getDoubleValue("MAPX");
                String distance = GpsUtil.getDistance(longitude, latitude, mapx, mapy);
                item.put("distance", "距离您约" + distance);
            }
            listViewAdapter.notifyDataSetChanged();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
